package com.atguigu.auth.controller;

import com.atguigu.auth.service.SysMenuService;
import com.atguigu.auth.service.SysUserService;
import com.atguigu.common.config.exception.GuiguException;
import com.atguigu.jwt.JwtHelper;
import com.atguigu.model.system.SysUser;
import com.atguigu.result.Result;
import com.atguigu.security.custom.LoginUserInfoHelper;
import com.atguigu.utils.MD5;
import com.atguigu.vo.system.LoginVo;
import com.atguigu.vo.system.RouterVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ClassName IndexController
 * Package: com.atguigu.auth.controller
 * ProjectName guigu-oa-parent
 * Description:
 *
 * @Author: 比特张
 * @Create: 2023/4/19 - 17:11
 * @Version: v1.0
 */
@Api(tags = "后台登录相关接口", value = "登录，退出，登录后个人信息")
@Slf4j
@RestController
@RequestMapping("/admin/system/index")
public class IndexController {

    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysMenuService sysMenuService;

    /**
     * 1，获取输入用户名和密码
     * 2，根据用户名查询数据库
     * 3，判断用户信息是否正确
     * 4，判断密码
     * 5，判断用户是否被禁用
     * 6，使用jwt根据用户id和用户名称生成token字符串
     * 7，返回
     *
     * @param loginVo
     * @return
     */
    @ApiOperation("登录")
    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo) {
        //        {"code":200,"data":{"token":"admin-token"}}
        //        Map<String, Object> map = new HashMap<>();
        //        map.put("token", "admin-token");
        //        return Result.ok(map);
        String username = loginVo.getUsername();
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername, username);
        SysUser sysUser = sysUserService.getOne(wrapper);

        if (sysUser == null) {
            throw new GuiguException(201, "该用户不存在！");
        }

        String backPassword = sysUser.getPassword();
        String encrypt = MD5.encrypt(loginVo.getPassword());
        if (!backPassword.equals(encrypt)) {
            throw new GuiguException(201, "密码错误！");
        }

        if (sysUser.getStatus().intValue() == 0) {
            throw new GuiguException(201, "该用户已被禁用！");
        }

        String token = JwtHelper.createToken(sysUser.getId(), sysUser.getUsername());

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        return Result.ok(map);
    }

    /**
     * 1，从请求头获取用户信息（获取请求头token字符串）
     * 2，从token字符串获取用户id或者用户名称
     * 3，根据用户id查询数据库，把用户信息获取出来
     * 4，根据用户id获取用户可以操作菜单列，查询数据库动态构建路由结构，进行显示
     * 5，根据用户id获取用户可以操作按钮列表
     * 6，返回相应的数据
     *
     * @param request
     * @return
     */
    @ApiOperation("登录获取个人信息")
    @GetMapping("/info")
    public Result info(HttpServletRequest request) {

        String token = request.getHeader("token");

        Long userId = JwtHelper.getUserId(token);
//        log.info("当前用户id：{}",userId.toString());

        SysUser sysUser = sysUserService.getById(userId);

        List<RouterVo> routerList = sysMenuService.findUserMenuListByUserId(userId);

        List<String> permsList = sysMenuService.findUserPermsByUserId(userId);

        Map<String, Object> map = new HashMap<>();
        map.put("roles", "[admin]");
        map.put("name", sysUser.getName());
        //头像
        map.put("avatar", "https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
        // 返回用户可以操作菜单
        map.put("routers", routerList);
        // 返回用户可以操作按钮
        map.put("buttons", permsList);
        return Result.ok(map);
    }

    /**
     * 退出要清空线程释放资源
     *
     * @return
     */
    @ApiOperation("退出")
    @PostMapping("/logout")
    public Result logout() {
        LoginUserInfoHelper.removeUserId();
        LoginUserInfoHelper.removeUsername();
        return Result.ok("退出成功");
    }
}
